package com.lz.servlet.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.util.IdUtil;
import com.google.gson.Gson;
import com.lz.common.annotation.AnonymousAccess;
import com.lz.common.baseBean.R;
import com.lz.common.utils.JwtUtil;
import com.lz.service.security.config.MyUserDetails;
import com.lz.servlet.domain.dto.LoginDTO;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;

import static com.lz.common.baseBean.StaticString.REDIS_CAPTCHA;
import static com.lz.common.baseBean.StaticString.REDIS_USER_LOGIN_COUNT;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private Gson gson;

    @Resource
    private RedisTemplate<String, String> redisTemplate;


    @GetMapping("/getCaptcha")
    @AnonymousAccess
    public R<HashMap<String, Object>> getCaptcha(String uuid) throws IOException {

        //如果存在旧的uuid则删除
        if (redisTemplate.hasKey(REDIS_CAPTCHA + uuid)) {
            redisTemplate.delete(REDIS_CAPTCHA + uuid);
        }

        // 生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        lineCaptcha.setGenerator(new RandomGenerator("0123456789", 4)); // 设置数字验证码生成器
        lineCaptcha.createCode(); // 生成验证码内容
// 获取 Base64 图片数据
        BufferedImage image = lineCaptcha.getImage();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", outputStream);
        String base64Image = "data:image/png;base64," + Base64.getEncoder().encodeToString(outputStream.toByteArray());

        // 生成唯一标识（用于后续校验）
        uuid = IdUtil.simpleUUID();
        // 构建返回值
        HashMap<String, Object> result = new HashMap<>();
        result.put("img", base64Image); // 返回 base64 图片
        result.put("uuid", uuid); // 返回唯一标识
        redisTemplate.opsForValue().set(REDIS_CAPTCHA + uuid, lineCaptcha.getCode(), 120, java.util.concurrent.TimeUnit.SECONDS); // 设置验证码缓存
        return R.success(result); // 返回成功响应
    }

    @PostMapping("/checkCaptcha")
    @AnonymousAccess
    public R<String> checkCaptcha(@RequestBody LoginDTO dto) {
        String username = dto.getUsername();
        String password = dto.getPassword();
        String uuid = dto.getUuid();
        String code = dto.getCode();


        String redisCode = redisTemplate.opsForValue().get(REDIS_CAPTCHA + uuid);
        redisTemplate.delete(REDIS_CAPTCHA + uuid);
        if (redisCode == null) {
            return R.error("验证码已过期");
        }
        if (!redisCode.equals(code)) {
            return R.error("验证码错误");
        }


        Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        if (authenticate == null) {
            throw new RuntimeException("用户名为空");
        }
        MyUserDetails userDetails = (MyUserDetails) authenticate.getPrincipal();
        String id = userDetails.getUser().getId();
        String json = gson.toJson(userDetails);

        redisTemplate.opsForValue().set(REDIS_USER_LOGIN_COUNT + id, json, 30 * 60, java.util.concurrent.TimeUnit.SECONDS);
        MyUserDetails a = gson.fromJson(json, MyUserDetails.class);
        System.out.println(a);
        String usernameFromToken = JwtUtil.createToken(id);
        return R.success(usernameFromToken);
    }


}
